以前通常會使用@Value來將application.properties的值注入類別變數:
application.yml
limit:
speed: 100
class Car
@Data
class Car{
String model;
@Value(speed.max)
String speed;
}
後來發現有個@ConfigurationProperties的註解可以很乾淨地做到注入Collection變數:
application.yml
nissan:
cars:
- model: sentra
speed: 100
- model: GTR
speed: 300
CarShop
@ConfigurationProperties(prefix = "nissan")
class CarShop{
List<Car> cars;
public List<Car> getCars(){
return cars;
}
public void setCars(List<Car> cars){
this.cars = cars;
}
}
只要這樣設定後,SpringBoot就會自動把application.yml中的nissan.cars注入到CarShop的cars類別變數。要做到這件事有幾個條件: